class GomokuGame {
    constructor() {
        this.canvas = document.getElementById('gameBoard');
        this.ctx = this.canvas.getContext('2d');
        this.currentPlayer = 1; // 1为黑子，-1为白子
        this.board = Array(15).fill(null).map(() => Array(15).fill(0));
        this.gameOver = false;
        this.moveHistory = [];
        
        this.initCanvas();
        this.bindEvents();
        this.drawBoard();
    }

    initCanvas() {
        // 设置画布大小
        this.canvasSize = 600;
        this.cellSize = this.canvasSize / 14;
        this.canvas.width = this.canvasSize;
        this.canvas.height = this.canvasSize;
        
        // 响应式调整
        this.adjustCanvasSize();
        window.addEventListener('resize', () => this.adjustCanvasSize());
    }

    adjustCanvasSize() {
        const container = this.canvas.parentElement;
        const maxSize = Math.min(container.clientWidth - 40, 600);
        
        if (maxSize < 600) {
            this.canvas.style.width = maxSize + 'px';
            this.canvas.style.height = maxSize + 'px';
        } else {
            this.canvas.style.width = '600px';
            this.canvas.style.height = '600px';
        }
    }

    bindEvents() {
        this.canvas.addEventListener('click', (e) => this.handleClick(e));
        document.getElementById('restartBtn').addEventListener('click', () => this.restart());
        document.getElementById('undoBtn').addEventListener('click', () => this.undo());
        document.getElementById('playAgainBtn').addEventListener('click', () => this.restart());
    }

    drawBoard() {
        this.ctx.clearRect(0, 0, this.canvasSize, this.canvasSize);
        
        // 绘制棋盘背景
        this.ctx.fillStyle = '#DEB887';
        this.ctx.fillRect(0, 0, this.canvasSize, this.canvasSize);
        
        // 绘制网格线
        this.ctx.strokeStyle = '#8B4513';
        this.ctx.lineWidth = 1;
        
        for (let i = 0; i < 15; i++) {
            // 横线
            this.ctx.beginPath();
            this.ctx.moveTo(this.cellSize, i * this.cellSize + this.cellSize);
            this.ctx.lineTo(this.canvasSize - this.cellSize, i * this.cellSize + this.cellSize);
            this.ctx.stroke();
            
            // 竖线
            this.ctx.beginPath();
            this.ctx.moveTo(i * this.cellSize + this.cellSize, this.cellSize);
            this.ctx.lineTo(i * this.cellSize + this.cellSize, this.canvasSize - this.cellSize);
            this.ctx.stroke();
        }
        
        // 绘制天元和星位
        const starPoints = [3, 7, 11];
        this.ctx.fillStyle = '#8B4513';
        starPoints.forEach(x => {
            starPoints.forEach(y => {
                this.ctx.beginPath();
                this.ctx.arc(
                    x * this.cellSize + this.cellSize,
                    y * this.cellSize + this.cellSize,
                    4, 0, 2 * Math.PI
                );
                this.ctx.fill();
            });
        });
        
        // 绘制棋子
        this.drawPieces();
    }

    drawPieces() {
        for (let row = 0; row < 15; row++) {
            for (let col = 0; col < 15; col++) {
                if (this.board[row][col] !== 0) {
                    this.drawPiece(row, col, this.board[row][col]);
                }
            }
        }
    }

    drawPiece(row, col, player) {
        const x = col * this.cellSize + this.cellSize;
        const y = row * this.cellSize + this.cellSize;
        const radius = this.cellSize * 0.4;
        
        // 绘制棋子阴影
        this.ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
        this.ctx.shadowBlur = 3;
        this.ctx.shadowOffsetX = 2;
        this.ctx.shadowOffsetY = 2;
        
        // 绘制棋子
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
        
        if (player === 1) {
            // 黑子
            const gradient = this.ctx.createRadialGradient(x - 5, y - 5, 0, x, y, radius);
            gradient.addColorStop(0, '#666');
            gradient.addColorStop(1, '#000');
            this.ctx.fillStyle = gradient;
        } else {
            // 白子
            const gradient = this.ctx.createRadialGradient(x - 5, y - 5, 0, x, y, radius);
            gradient.addColorStop(0, '#fff');
            gradient.addColorStop(1, '#ddd');
            this.ctx.fillStyle = gradient;
        }
        
        this.ctx.fill();
        
        // 重置阴影
        this.ctx.shadowColor = 'transparent';
        this.ctx.shadowBlur = 0;
        this.ctx.shadowOffsetX = 0;
        this.ctx.shadowOffsetY = 0;
    }

    handleClick(e) {
        if (this.gameOver) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const scaleX = this.canvas.width / rect.width;
        const scaleY = this.canvas.height / rect.height;
        
        const x = (e.clientX - rect.left) * scaleX;
        const y = (e.clientY - rect.top) * scaleY;
        
        const col = Math.round((x - this.cellSize) / this.cellSize);
        const row = Math.round((y - this.cellSize) / this.cellSize);
        
        // 检查是否在有效范围内
        if (row < 0 || row >= 15 || col < 0 || col >= 15) return;
        
        // 检查该位置是否已有棋子
        if (this.board[row][col] !== 0) return;
        
        // 落子
        this.makeMove(row, col);
    }

    makeMove(row, col) {
        this.board[row][col] = this.currentPlayer;
        this.moveHistory.push({row, col, player: this.currentPlayer});
        
        this.drawBoard();
        
        // 检查胜负
        if (this.checkWin(row, col)) {
            this.gameOver = true;
            const winner = this.currentPlayer === 1 ? '黑子' : '白子';
            this.showWinMessage(`${winner}获胜！`);
            document.getElementById('undoBtn').disabled = true;
            return;
        }
        
        // 检查平局
        if (this.checkDraw()) {
            this.gameOver = true;
            this.showWinMessage('平局！');
            document.getElementById('undoBtn').disabled = true;
            return;
        }
        
        // 切换玩家
        this.currentPlayer *= -1;
        this.updateCurrentPlayerDisplay();
        
        // 启用悔棋按钮
        document.getElementById('undoBtn').disabled = false;
    }

    checkWin(row, col) {
        const directions = [
            [0, 1],   // 水平
            [1, 0],   // 垂直
            [1, 1],   // 对角线
            [1, -1]   // 反对角线
        ];
        
        const player = this.board[row][col];
        
        for (const [dx, dy] of directions) {
            let count = 1;
            
            // 正向检查
            for (let i = 1; i < 5; i++) {
                const newRow = row + dx * i;
                const newCol = col + dy * i;
                
                if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15) break;
                if (this.board[newRow][newCol] !== player) break;
                
                count++;
            }
            
            // 反向检查
            for (let i = 1; i < 5; i++) {
                const newRow = row - dx * i;
                const newCol = col - dy * i;
                
                if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15) break;
                if (this.board[newRow][newCol] !== player) break;
                
                count++;
            }
            
            if (count >= 5) return true;
        }
        
        return false;
    }

    checkDraw() {
        for (let row = 0; row < 15; row++) {
            for (let col = 0; col < 15; col++) {
                if (this.board[row][col] === 0) return false;
            }
        }
        return true;
    }

    updateCurrentPlayerDisplay() {
        const playerText = this.currentPlayer === 1 ? '黑子' : '白子';
        const playerClass = this.currentPlayer === 1 ? 'player-black' : 'player-white';
        
        const element = document.getElementById('currentPlayer');
        element.textContent = playerText;
        element.className = playerClass;
    }

    showWinMessage(message) {
        document.getElementById('winMessage').textContent = message;
        document.getElementById('winModal').style.display = 'block';
    }

    restart() {
        this.board = Array(15).fill(null).map(() => Array(15).fill(0));
        this.currentPlayer = 1;
        this.gameOver = false;
        this.moveHistory = [];
        
        this.drawBoard();
        this.updateCurrentPlayerDisplay();
        document.getElementById('undoBtn').disabled = true;
        document.getElementById('winModal').style.display = 'none';
    }

    undo() {
        if (this.moveHistory.length === 0 || this.gameOver) return;
        
        const lastMove = this.moveHistory.pop();
        this.board[lastMove.row][lastMove.col] = 0;
        this.currentPlayer = lastMove.player;
        
        this.drawBoard();
        this.updateCurrentPlayerDisplay();
        
        if (this.moveHistory.length === 0) {
            document.getElementById('undoBtn').disabled = true;
        }
    }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    new GomokuGame();
});
